
/**
 * AJAX/XMLHTTPREQUEST WRAPPER CLASS
 */
function AjaxWrap() {

    //Vars
    this.xhr = createXHR();
    this.xhr.ajWrap             = this;

    //Callback functions, set it from outside.
    this.onStateChanged         = function(ajWrap) {} //Callback when state changed
    this.onLoadSuccess          = function(ajWrap) {} //Callback when load succeed
    this.onLoadError            = function(ajWrap) {} //Callback when load error
    this.onConnectionOpened     = function(ajWrap) {} //Callback after calling open()
    this.onLoading              = function(ajWrap) {} //Callback when state changed to loading

    //public function
    this.openAndSend = function(method, url, async, request) {
        this.xhr.open(method, url, async);
        if(method == 'POST') this.xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        this.xhr.send(request);
    }

    //private function
    this.xhr.onreadystatechange = function () {
        var ajWrap  = this.ajWrap;
        var state   = this.readyState;
        
        ajWrap.onStateChanged(ajWrap);
        if(state == 1)  {
            ajWrap.onConnectionOpened(ajWrap);
        }
        else if(state == 2) {
            ajWrap.onLoading(ajWrap);
        }
        else if(state == 4) {
            if(this.status == 200) ajWrap.onLoadSuccess(ajWrap);
            else ajWrap.onLoadError(ajWrap);
        }
    }
    
    return this.xhr == null ? null : this;
}



function createXHR()
{
    var request = false;
        try {
            request = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (err2) {
            try {
                request = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (err3) {
		try {
			request = new XMLHttpRequest();
		}
		catch (err1)
		{
			request = false;
		}
            }
        }
    return request;
}